<template>
  <el-form ref="dataDetails" class="form-table" v-loading="loading" :model="dataDetails" :rules="ruleValidate"
    label-width="130px" @submit.native.prevent>
    <div style="display: flex;width: 100%">
      <div style="display: flex;flex-direction: column;width: 100%">
        <div style="display: flex;">
          <div style="flex: 1">
            <el-form-item label="活动主题：" prop="activityName">
              <el-input class="form-input" :maxlength="20" show-word-limit v-model="dataDetails.activityName"/>
            </el-form-item>
            <el-form-item label="通知内容：" prop="content" v-if="!isFlag(dataDetails.activityType,1)">
              <el-input type="textarea" :autosize="{minRows:2}" :maxlength="200" show-word-limit class="form-input" v-model="dataDetails.content"/>
            </el-form-item>
            <el-form-item label="开始时间：" v-if="!isFlag(dataDetails.activityType,1)">
              <el-date-picker v-model="dataDetails.beginDate" type="datetime" placeholder="选择开始时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="负责人员：" prop="chargePerson">
              <el-input class="form-input" :maxlength="20" show-word-limit v-model="dataDetails.chargePerson"/>
            </el-form-item>
            <el-form-item label="播放时长：" prop="duration" v-if="!isFlag(dataDetails.activityType,1)">
              <el-input-number class="form-input" :min="1" v-model="dataDetails.duration"/>
              秒
            </el-form-item>
            <el-form-item label="推送账号：" prop="duration">
              <el-select v-model="dataDetails.businessPhoneList" clearable filterable multiple class="form-input" placeholder="请选择">
                <el-option v-for="(item,index) in businessPojoList" :value="item.phone" :label="item.phone+'('+item.businessName+')'" :key='index'/>
              </el-select>
            </el-form-item>
          </div>
          <div style="flex: 1">
            <div>
              <el-form-item label="上传音频：" v-if="!isFlag(dataDetails.activityType,1)">
                <el-upload style="width: 300px;" action="#" accept=".mp3" ref="upload"
                  :click="handleClick" :before-upload="handleChange" :file-list="fileList">
                  <div slot="file" slot-scope="{file}">
                    <div v-for="(item,index) in fileList" :key="index" style="font-size: 18px;display: flex;justify-content: space-between">
                      <div @click="handleClick(item)">
                        <i class="el-icon-s-order"></i>{{ item.name }}
                      </div>
                      <div>
                        <el-button @click="handleRemove(index)" type="danger" size="mini" icon="el-icon-delete" circle></el-button>
                      </div>
                    </div>
                  </div>
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item label="活动图片：" prop="avatarUrl" v-if="isFlag(dataDetails.activityType,0)">
                <avatar-upload ref="avatarUrl" :imgUrl.sync="windowImg" :size="2"/>
              </el-form-item>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div style="margin-left: 35%">
      <el-button type="primary" round class="table-button-param" @click="handleSubmit('dataDetails')">提交</el-button>
      <el-button type="primary" round @click="handleReturn" class="table-button-param">返回</el-button>
    </div>
    <div>
      <el-dialog width="30%" :visible.sync="dialogVisible" append-to-body>
        <img class="image-details" :src="dialogImageUrl" alt="">
      </el-dialog>
    </div>
  </el-form>
</template>

<script>
import '@/styles/style.scss'
import '@/styles/upload.scss'
import appUtils, {formatDate, isBlank, isFlag, moneyFormat, ossPut} from '@/utils/util'
import ruleUtils from '@/utils/ruleUtils'
import {fileUrlUtils, imageUtils} from '@/utils/imageUtil'
import {dateToString} from '@/utils/dateUtils'
import avatarUpload from '@/components/Upload/avatarUpload'
import {
  displayWindowBusinessNoPageCopy, displayPartnerNoticePojoDetails, displayWindowNoticePojoOperation
} from '@/api/display'
import options from '@/utils/cities'
import VideoUpload from '@/components/Upload/videoUpload'

export default {
  components: {
    appUtils,
    avatarUpload,
    VideoUpload
  },
  data() {
    const avatarUrlValidator = (rule, value, callback) => {
      if (isBlank(this.$store.state.avatarUpload) && isBlank(this.$store.state.avatarUrl)) {
        return callback(new Error('请上传封面'))
      }
      return callback()
    }
    return {
      props: {
        multiple: true,
        checkStrickly: true
      },
      activityId: this.$route.query.activityId,
      paId: this.$store.state.user.userId,
      myImage: appUtils.myImage,
      windowImg: appUtils.windowImg,
      dataDetails: {
        chargePerson: '',
        duration: 1,
        activityType: this.$route.query.activityType,
        labelNameList: [],
        deviceIdList: [],
        businessPhoneList: [],
      },
      options: options,
      dialogImageUrl: '',
      cover: '',
      search: '',
      bgMp3: '',
      productName: '',
      dialogVisible: false,
      loading: false,
      imageUrl: '',
      coverUpload: {},
      dataList: [],
      businessPojoList: [],
      routerPage: [],
      fileList: [],
      advertDevicePojoList: [],
      labelList: [],
      deviceIdList: [],
      checkAllGroup: [],
      ruleValidate: {
        activityName: [{
          required: true,
          message: '请输入活动主题',
          validator: ruleUtils.nullValidator,
          trigger: 'blur'
        }],
        duration: [{
          required: true,
          message: '请输入播放时长',
          validator: ruleUtils.nullValidator,
          trigger: 'blur'
        }],
        deviceIdList: [{
          required: true,
          message: '请选择设备',
          validator: ruleUtils.nullValidator,
          trigger: 'blur'
        }],
        liveTime: [{
          required: true,
          message: '请选择直播时间',
          validator: ruleUtils.nullValidator,
          trigger: 'blur'
        }],
        'avatarUrl': [{
          required: true,
          validator: avatarUrlValidator,
          trigger: 'blur'
        }],
      },
    }
  },
  methods: {
    isBlank,
    isFlag,
    dateToString,
    moneyFormat,
    formatDate,
    imageUtils,
    handleSubmit(name) {
      this.$confirm('是否确认提交', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(_ => {
        this.$refs[name].validate(valid => {
            if (valid) {
              this.loading = true
              let avatarUpload = this.$store.state.avatarUpload
              if (!isBlank(avatarUpload)) {
                this.cover = ossPut(avatarUpload, appUtils.windowImg)
              }
              if (!isBlank(this.cover) && isFlag(this.dataDetails.activityType, 0)) {
                this.dataDetails.fileUrl = this.cover
              }
              if (this.fileList.length > 0) {
                if (!isBlank(this.fileList[0].file)) {
                  this.bgMp3 = ossPut(this.fileList[0].file, appUtils.windowImg)
                }
              }
              console.log('this.bgMp3', this.bgMp3)
              this.dataDetails.bgMp3 = this.bgMp3
              this.dataDetails.paId = this.paId
              const dataDetailsJson = JSON.stringify(this.dataDetails)
              console.log(dataDetailsJson)
              displayWindowNoticePojoOperation(dataDetailsJson).then(res => {
                console.log(res)
                if (isFlag(res.code, 1)) {
                  this.$message.success(res.message)
                  this.handleReturn()
                } else {
                  this.$message.error(res.message)
                }
                this.loading = false
              })
            }
          }
        )
      }).catch(_ => {
      });
    },
    handleReturn() {
      this.$router.go(-1)
    },
    handleRemove(index) {
      this.fileList.splice(index, 1)
      this.bgMp3 = ''
    },
    handleClick(item) {
      let audio = new Audio()//在VUE中使用audio标签
      audio.src = item.url//设置audio的src为上面生成的url
      audio.play()//进行播放
    },
    handleChange(file) {
      this.fileList = []
      this.$nextTick(() => {
        this.fileList.push({
          name: file.name,
          url: file.url,
          file: file
        })
      })
      return false
    },
    handleInput2(e) {
      var number = e.target.value.slice(0, 11)
      e.target.value = (number.match(/^\d*(\.?\d{0,1})/g)[0]) || null
    },
  },
  mounted() {
    this.activityId = this.$route.query.activityId
    this.dataDetails.activityType = this.$route.query.activityType
    displayWindowBusinessNoPageCopy(this.paId).then(res => {
      console.log(res.data)
      this.businessPojoList = res.data.dataList
    })
    if (!isBlank(this.activityId)) {
      displayPartnerNoticePojoDetails(this.activityId).then(res => {
        console.log('res.data', res.data)
        this.dataDetails = res.data.advertActivityPojo
        if (!isFlag(this.dataDetails.activityType, 1)) {
          if (!isBlank(this.dataDetails.bgMp3)) {
            this.bgMp3 = this.dataDetails.bgMp3
            this.fileList.push({
              name: this.dataDetails.bgMp3,
              url: fileUrlUtils(this.windowImg, this.dataDetails.bgMp3)
            })
          }
        }
        if (!isBlank(this.dataDetails.fileUrl) && !isFlag(this.dataDetails.activityType, 1)) {
          this.$store.state.avatarUrl = this.dataDetails.fileUrl
          if (isFlag(this.dataDetails.activityType, 0)) {
            this.$nextTick(() => {
              this.$refs['avatarUrl'].updateUrl()
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
